package com.sctvcloud.bazhong.ui.activities;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.beans.LicenseKeyItem;
import com.sctvcloud.bazhong.beans.LiveAdvance;
import com.sctvcloud.bazhong.beans.LiveAdvanceInfo;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.http.ParamsEditor;
import com.sctvcloud.bazhong.ui.activities.wowza.CameraActivity;
import com.sctvcloud.bazhong.ui.dialog.ChannelDiaFragment;
import com.sctvcloud.bazhong.ui.utils.TitleUtils;
import com.sctvcloud.bazhong.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 发起直播
 */
public class LiveBroadcastActivity extends BaseActivity {
    @BindView(R.id.live_choice_channel)
    protected CustomFontTextView liveName;
    @BindView(R.id.live_choice_codeCheck)
    protected CustomFontTextView liveRate;
    @BindView(R.id.live_choice_resolving_power)
    protected CustomFontTextView liveWH;
    private ChannelDiaFragment channelDiaFragment;
    public static final String CHANNEL_TAG = "dia_channel_fragment";
    private ArrayList<LiveAdvanceInfo> liveAdvanceInfos;

    private LiveAdvanceInfo advanceInfo;
    private String tempName = "";
    private String tempRate = "";
    private String tempWh = "";
    private String licenseKey = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        advanceInfo = new LiveAdvanceInfo();
        getLicenseKey();
        getLiveConfig();
    }

    /**
     * 请求LicenseKey
     */
    private void getLicenseKey() {
        Map<String, Object> param = new HashMap<>();
        param.put("licenseType", "1");
        NetUtils.getNetAdapter().getLicensekey(getOwnerName(), param, new AbsNetCallBack<LicenseKeyItem>(LicenseKeyItem.class) {
            @Override
            public void onSuc(LicenseKeyItem licenseKeyItem) {
                licenseKey = licenseKeyItem.getLicenseKey();
            }
        });

    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_live_broadcast);
        ButterKnife.bind(this);
    }

    /**
     * 请求直播配置数据
     */
    private void getLiveConfig() {
        if (!UserManager.isLoginS()) {
            return;
        }
        ParamsEditor pe = new ParamsEditor();
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        NetUtils.getNetAdapter().getLiveConfig(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken())
                , new AbsNetCallBack<LiveAdvance>(LiveAdvance.class) {
                    @Override
                    public void onSuc(LiveAdvance liveAdvance) {
                        if (liveAdvance != null) {
                            JLog.e(liveAdvance.toString());
                            liveAdvanceInfos = liveAdvance.getList();
                        }
                    }
                });
    }

    @OnClick(value = {R.id.live_channel, R.id.live_ticket, R.id.live_code_check, R.id.live_resolving_power})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.live_channel:
                if (!ListUtils.isListValued(liveAdvanceInfos)) {
                    Toast.makeText(this, "直播配置数据错误，请联系管理员！", Toast.LENGTH_SHORT).show();
                    return;
                }
                channelDiaFragment = new ChannelDiaFragment();
//                if (channelDiaFragment == null) {
//                }
                channelDiaFragment.setOnSelectedListener(new ChannelDiaFragment.OnSelectedListener() {
                    @Override
                    public void onSelected(LiveAdvanceInfo info) {
                        JLog.e("Click:" + info.toString());
                        if (info != null) {
                            liveName.setText(info.getName());
                            tempName = info.getName();
                            advanceInfo.setAddress(info.getAddress());
                        }
                        channelDiaFragment.dismissAllowingStateLoss();
                    }
                });
                channelDiaFragment.setDatas(liveAdvanceInfos);
                channelDiaFragment.setSelectedData(tempName);
                safeShowDialog(channelDiaFragment, CHANNEL_TAG);
               // channelDiaFragment.show(getSupportFragmentManager(), CHANNEL_TAG);
                break;
            case R.id.live_ticket:
                break;
            case R.id.live_code_check:
                Resources res = getResources();
                String[] rateStr = res.getStringArray(R.array.video_bit_rate);
                int[] rate = res.getIntArray(R.array.video_kbps);
                if (rateStr.length != rate.length) {
                    return;
                }
                ArrayList<LiveAdvanceInfo> infos = new ArrayList<>();
                for (int i = 0; i < rateStr.length; i++) {
                    LiveAdvanceInfo info = new LiveAdvanceInfo();
                    String name = rateStr[i];
                    int rateNumber = rate[i];
                    info.setName(name);
                    info.setRate(rateNumber);
                    infos.add(info);
                }
//                if (channelDiaFragment == null) {
//                }
                channelDiaFragment = new ChannelDiaFragment();
                channelDiaFragment.setOnSelectedListener(new ChannelDiaFragment.OnSelectedListener() {
                    @Override
                    public void onSelected(LiveAdvanceInfo info) {
                        JLog.e("Click:" + info.toString());
                        if (info != null) {
                            liveRate.setText(info.getName());
                            tempRate = info.getName();
                            advanceInfo.setRate(info.getRate());
                        }
                        channelDiaFragment.dismissAllowingStateLoss();
                    }
                });

                channelDiaFragment.setDatas(infos);
                channelDiaFragment.setSelectedData(tempRate);
                channelDiaFragment.show(getSupportFragmentManager(), CHANNEL_TAG);
                break;
            case R.id.live_resolving_power:
                Resources wh_res = getResources();
                String[] wh_Str = wh_res.getStringArray(R.array.video_width_height);
                int[] width = wh_res.getIntArray(R.array.video_width);
                int[] height = wh_res.getIntArray(R.array.video_height);
                if (wh_Str.length != width.length || wh_Str.length != height.length) {
                    return;
                }
                ArrayList<LiveAdvanceInfo> wh_infos = new ArrayList<>();
                for (int i = 0; i < wh_Str.length; i++) {
                    LiveAdvanceInfo info = new LiveAdvanceInfo();
                    info.setName(wh_Str[i]);
                    info.setHeight(height[i]);
                    info.setWidth(width[i]);
                    wh_infos.add(info);
                }
//                if (channelDiaFragment == null) {
//                }
                channelDiaFragment = new ChannelDiaFragment();
                channelDiaFragment.setOnSelectedListener(new ChannelDiaFragment.OnSelectedListener() {
                    @Override
                    public void onSelected(LiveAdvanceInfo info) {
                        JLog.e("Click:" + info.toString());
                        if (info != null) {
                            liveWH.setText(info.getName());
                            tempWh = info.getName();
                            advanceInfo.setHeight(info.getHeight());
                            advanceInfo.setWidth(info.getWidth());
                        }
                        channelDiaFragment.dismissAllowingStateLoss();
                    }
                });

                channelDiaFragment.setDatas(wh_infos);
                channelDiaFragment.setSelectedData(tempWh);
                channelDiaFragment.show(getSupportFragmentManager(), CHANNEL_TAG);
                break;
        }
    }


    @OnClick(value = R.id.live_start_living)
    public void startLivingClick(View view) {
        if (TextUtils.isEmpty(advanceInfo.getAddress())) {
            Toast.makeText(this, R.string.choice_live_channel, Toast.LENGTH_SHORT).show();
            return;
        }
        if (advanceInfo.getRate() == -1) {
            Toast.makeText(this, "请选择推流码率", Toast.LENGTH_SHORT).show();
            return;
        }
        if (advanceInfo.getHeight() == -1 || advanceInfo.getWidth() == -1) {
            Toast.makeText(this, "请选择推流分辨率", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, CameraActivity.class);
        intent.putExtra("data", advanceInfo);
        intent.putExtra("key", licenseKey);
        startActivity(intent);
    }
}
